package org.kl.bf.web.basic;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.kl.bf.entity.basic.Organization;
import org.kl.bf.entity.basic.Post;
import org.kl.bf.entity.basic.Staffinfo;
import org.kl.bf.entity.easyui.EasyuiGrid;
import org.kl.bf.entity.easyui.EasyuiTreeNode;
import org.kl.bf.service.basic.OrganizationService;
import org.kl.bf.service.basic.PostService;
import org.kl.bf.service.basic.StaffinfoService;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springside.modules.utils.Collections3;
import org.springside.modules.web.MediaTypes;

/**
 * 岗位分配
 * 
 * @Author ymc
 * @CreateTime 2014-3-13 下午9:34:36
 */
@Controller
@RequestMapping(value = "/basic/postUsers")
public class PostUsersController extends BasicController {

	@Autowired
	private StaffinfoService staffinfoService;
	@Autowired
	protected OrganizationService organizationService;
	@Autowired
	protected PostService postService;

	Set<Post> postSet = new HashSet<Post>();

	@RequiresPermissions("postUsers:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/postUsersList";
	}

	@SuppressWarnings("unchecked")
	@RequiresPermissions("postUsers:list")
	@RequestMapping(value = "tree", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String tree(@RequestParam(value = "id", defaultValue = "") String id, Model model, ServletRequest request) {
		List<Organization> organizationList = new ArrayList<Organization>();
		if (StringUtils.isBlank(id)) {
			List<Organization> root = organizationService.findRoot();
			if (root != null) {
				organizationList.addAll(root);
			}
			List<Organization> rootChildren = organizationService.findByOrganizationsParentOrgIdIn(Collections3.extractToList(root, "id"));

			if (rootChildren != null) {
				organizationList.addAll(rootChildren);
			}
		} else {
			organizationList = organizationService.findByOrgNo(id);
		}
		List<EasyuiTreeNode> plainTree = new ArrayList<EasyuiTreeNode>();
		for (Organization organization : organizationList) {
			EasyuiTreeNode one = organizationToTreeNode(organization);
			plainTree.add(one);
		}
		String result = jsonMapper.toJson(plainTree);
		return result;
	}

	private EasyuiTreeNode organizationToTreeNode(Organization organization) {
		EasyuiTreeNode one = new EasyuiTreeNode();
		one.setId(organization.getId());
		if (StringUtils.isBlank(organization.getParentOrgId())) {
			one.setText("组织--" + organization.getOrgName());
		} else {
			one.setText("子组织--" + organization.getOrgName());
		}
		one.setPid(organization.getParentOrgId());
		Map<String, Object> attributes = new HashMap<String, Object>();
		attributes.put("orgNo", organization.getOrgNo());
		attributes.put("parentOrgId", organization.getParentOrgId());
		attributes.put("zipCode", organization.getZipCode());
		attributes.put("enable", organization.getEnable());
		attributes.put("address", organization.getAddress());
		attributes.put("description", organization.getDescription());
		attributes.put("fax", organization.getFax());
		attributes.put("phoneNumber", organization.getPhoneNumber());
		one.setAttributes(attributes);
		List<Post> postList = postService.findByOrganizationIdAndEnable(organization.getId());
		List<EasyuiTreeNode> postTree = new ArrayList<EasyuiTreeNode>();
		for (Post p : postList) {
			EasyuiTreeNode two = postToTreeNode(p);
			postTree.add(two);
		}
		one.setChildren(postTree);
		if (StringUtils.isNotBlank(organization.getParentOrgId()) && organizationService.childrenCount(organization.getOrgNo()) > 0) {
			one.setState("closed");
		}
		return one;
	}

	private EasyuiTreeNode postToTreeNode(Post post) {
		EasyuiTreeNode two = new EasyuiTreeNode();
		two.setId(post.getId());
		two.setIconCls("icon-hamburg-issue");
		two.setText("岗位--" + post.getPostName());
		two.setPid(post.getOrganization().getId());
		Map<String, Object> attributes = new HashMap<String, Object>();
		attributes.put("postNo", post.getPostNo());
		attributes.put("postName", post.getPostName());
		attributes.put("organization", post.getOrganization());
		attributes.put("description", post.getDescription());
		attributes.put("id", post.getId());
		two.setAttributes(attributes);
		return two;
	}

	@RequiresPermissions("postUsers:list")
	@RequestMapping(value = "dataGrid/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			@PathVariable("id") String postid) {
		Post p = postService.getOnePost(postid);
		List<Staffinfo> staffinfoList = new ArrayList<Staffinfo>();
		staffinfoList = staffinfoService.getAllStaffinfo();
		for (int i = staffinfoList.size() - 1; i >= 0; i--) {
			Staffinfo s = staffinfoList.get(i);
			if (s.getPostSet().isEmpty()) {
				staffinfoList.remove(s);
			} else if (!s.getPostSet().contains(p)) {
				staffinfoList.remove(s);
			}
		}
		List<Staffinfo> sList = new ArrayList<Staffinfo>();
		for (int i = (pageNumber - 1) * pageSize; i < pageNumber * pageSize && i < staffinfoList.size(); i++) {
			Staffinfo st = staffinfoList.get(i);
			sList.add(st);
		}
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(sList);
		grid.setTotal(staffinfoList.size());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	@RequiresPermissions("postUsers:list")
	@RequestMapping(value = "showInfo/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String showInfo(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request,
			@PathVariable("id") String postid) {
		Post p = postService.getOnePost(postid);
		List<Staffinfo> staffinfoList = new ArrayList<Staffinfo>();
		staffinfoList = staffinfoService.getAllStaffinfo();
		for (int i = staffinfoList.size() - 1; i >= 0; i--) {
			Staffinfo s = staffinfoList.get(i);
			if ((!s.getPostSet().isEmpty()) && s.getPostSet().contains(p)) {
				staffinfoList.remove(s);
			}
		}
		List<Staffinfo> sList = new ArrayList<Staffinfo>();
		for (int j = (pageNumber - 1) * pageSize; j < pageNumber * pageSize && j < staffinfoList.size(); j++) {
			Staffinfo st = staffinfoList.get(j);
			sList.add(st);
		}
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(sList);
		grid.setTotal(staffinfoList.size());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	@RequiresPermissions("postUsers:add")
	@RequestMapping(value = "addPost", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String addPost(ServletRequest request) {
		String ids = request.getParameter("userIds");
		String postId = request.getParameter("postId");
		if (StringUtils.isBlank(ids)) {
			return ajaxMsg("添加失败，用户Id不能为空!", false, null);
		}
		if (StringUtils.isBlank(postId)) {
			return ajaxMsg("添加失败，岗位Id不能为空!", false, null);
		}
		String[] userIds = ids.split(",");
		try {
			for (String id : userIds) {
				Staffinfo s = staffinfoService.getOneStaffinfo(id);
				postSet = s.getPostSet();
				Post p = postService.getOnePost(postId);
				postSet.add(p);
				s.setPostSet(postSet);
				staffinfoService.saveStaffinfo(s);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("添加失败[" + e.getMessage() + "]", false, null);
		}
		return ajaxMsg("添加成功", true, null);
	}

	@RequiresPermissions("postUsers:delete")
	@RequestMapping(value = "removePost", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String removePost(ServletRequest request) {
		String ids = request.getParameter("userIds");
		String postId = request.getParameter("postId");
		if (StringUtils.isBlank(ids)) {
			return ajaxMsg("删除失败，用户Id不能为空!", false, null);
		}
		if (StringUtils.isBlank(postId)) {
			return ajaxMsg("删除失败，岗位Id不能为空!", false, null);
		}
		Post p = postService.getOnePost(postId);
		String[] userIds = ids.split(",");
		int i = 0;
		try {
			for (String id : userIds) {
				Staffinfo s = staffinfoService.getOneStaffinfo(id);
				postSet = s.getPostSet();
				if (!StringUtils.equals(postId, s.getPost().getId())) {
					if (postSet.contains(p)) {
						postSet.remove(p);
						s.setPostSet(postSet);
					}
					staffinfoService.saveStaffinfo(s);
				} else {
					i++;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败[" + e.getMessage() + "]", false, null);
		}
		return ajaxMsg("删除成功,忽略"+i+"个主岗位为该岗位的员工", true, null);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getPost(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("post", postService.getPost(id));
		}
	}
}
